package com.huajx.core.util;

import com.huajx.util.HexUtil;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public abstract class MessageKit {
//	private static final Logger logger = LoggerFactory.getLogger(MessageKit.class);

    public static String getStr(byte[] bytes, int start, int len) {
        int bLen = bytes.length;

        int to = start + len;

        if (bLen < to) {
            to = bLen;
        }

        return bytesToString(Arrays.copyOfRange(bytes, start, to));
    }

    public static int getInt(byte[] bytes, int start, int len) {
        int bLen = bytes.length;

        int to = start + len;

        if (bLen < to) {
            to = bLen;
        }

        return bytes2Int(Arrays.copyOfRange(bytes, start, to));
    }

    // byte数组长度为4, bytes[3]为高8位
    public static int bytes2Int(byte[] bytes) {
        int value = 0;
//		String str = "0x"+bytesToString(bytes);
        value = Integer.parseInt(bytesToString(bytes), 16);
//		value = ((bytes[3] & 0xff) << 24) | ((bytes[2] & 0xff) << 16) | ((bytes[1] & 0xff) << 8) | (bytes[0] & 0xff);
        return value;
    }

    public static String bytesToString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length);

        for (int i = 0; i < bytes.length; i++) {
            sb.append((char) bytes[i]); // 可以根据需要自己改变类型
        }

//		logger.info(sb.toString());

        return sb.toString();
    }

   /* public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length);
        for (int i = 0; i < bytes.length; i++) {
            String strHex = Integer.toHexString(bytes[i]);
            int len = strHex.length();
            if (len > 6) {
                strHex = strHex.substring(6, len);
            }
            sb.append(strHex).append(','); // 可以根据需要自己改变类型
        }
        return sb.toString();
    }*/
    /**
     * byte数组转hex
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes){
        return HexUtil.bytesToHex(bytes);
    }


    /**
     * int 转 16进制
     *
     * @param n
     * @return
     */
    public static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
        	//System.out.println(n);
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        return a;
    }

    /**
     * 转16进制字符串，并左补相应字符，如0或空格，多了截取
     *
     * @param n      10进制值
     * @param prefix 前缀
     * @param num    需补位数
     * @return
     */
    public static String intToHex(int n, char prefix, int num) {
        String s = intToHex(n);
        int len = s.length();
        if (len > num) {
            return s.substring(len - num, len);
        } else if (len == num) {
            return s;
        } else {
            StringBuilder sb = new StringBuilder();
            for (int i = 0, ll = num - len; i < ll; i++) {
                sb.append(prefix);
            }
            sb.append(s);
            return sb.toString();
        }
    }


    /**
     * 天波校验和
     *
     * @param s
     * @return
     */
    public static String checksum(String s) {
        byte[] bs = s.getBytes();
        int i = 0;
        for (byte b : bs) {
            i += b;
        }

        return intToHex(i, '0', 2);
    }
    /**
     * udp校验和
     * @param hexdata
     * @return
     */
    public static String makeChecksum(String hexdata) {
        if (hexdata == null || hexdata.equals("")) {
            return "00";
        }
        hexdata = hexdata.replaceAll(" ", "");
        int total = 0;
        int len = hexdata.length();
        if (len % 2 != 0) {
            return "00";
        }
        int num = 0;
        while (num < len) {
            String s = hexdata.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        return hexInt(total);
    }
    /**
     * 高低位互换
     * @param str
     */
    public static String chang(String str){
    	String str2 = ""; 
    	for (int i = str.length() - 2; i >= 0; ){
            str2 += str.substring(i, i+2);
            i=i-2;
        }
    	return str2;
    }
     
    private static String hexInt(int total) {
        int a = total / 256;
        int b = total % 256;
        if (a > 255) {
            return hexInt(a) + format(b);
        }
        return format(a) + format(b);
    }
     
    private static String format(int hex) {
        String hexa = Integer.toHexString(hex);
        int len = hexa.length();
        if (len < 2) {
            hexa = "0" + hexa;
        }
        return hexa;
    }
    
    /**
     * 控制校验和
     *
     * @param s
     * @return
     */
     public static String udpChecksum(String  str) {
    	byte[] bs = str.getBytes();
        int i = 0;
        for (byte b : bs) {
            i += b;
        }
        System.out.println(i);
        return String.valueOf(i);
     }
     
  public static String decodeHexString(String str) {
	  str =HighLowHex(spaceHex(str));
	  String value =new BigInteger(str, 16).toString();
	  return value;
  }

  public static String spaceHex(String str){
	 char[] array= str.toCharArray();
	 if(str.length()<=2) return str;
	 StringBuffer buffer =new StringBuffer();
	 for(int i=0;i<array.length;i++){
		 int start =i+1;
		 if(start%2==0){
			 buffer.append(array[i]).append(" ");
		 }else{
			 buffer.append(array[i]);
		 }
	 }
	 	return buffer.toString();
	}

	public static String HighLowHex(String str){
		if(str.trim().length()<=2) return str;
		List<String> list = Arrays.asList( str.split(" "));
		Collections.reverse(list);
		StringBuffer stringBuffer = new StringBuffer();
		for(String string:list){
			stringBuffer.append(string);
		}
		return stringBuffer.toString();
	}
	/**
	 * 取出校验和并高低位互换
	 */
	public static String checkSumChang(String str){
		 String checksum = makeChecksum(str);
		 String changSum = chang(checksum);
		 return changSum;
	}
	
    public static void main(String[] args) {
    	 String fillzero = fillzero(14, 8);
    	 System.out.println(chang("953b"));
     }
     /**
      * 补零并高低位互换
      * @param no
      * @param length
      * @return
      */
     public static String fillzero(int no,int length){
    	 String orderno = intToHex(no);
    	 if(orderno.length()<length){
    		 int z=length-orderno.length();
    		 for( int i=0;i<z;i++){
    			 orderno="0"+orderno;
    		 } 
    	 }
    	 return chang(orderno); 
     }
}
